import XEUtils from 'xe-utils'
import { getDeptUsersTree } from '@/api/system/user/index'
import { VxeUI } from 'vxe-table'
import { UserConfigApi } from '@/api/task/userconfig'
import * as MenuApi from '@/api/system/increase'

const defaultData = {
  id: null,
  sn: '',
  taskName: '',
  status: 0,
  publisherId: '',
  taskStartTime: new Date(),
  taskEndTime: '',
  responsibleId: '',
  priority: 0,
  explanation: '',
  taskType: 1
}
//状态
const statusOptions = [
  { label: '未完成', value: 0 },
  { label: '已完成', value: 1 }
]
//优先级
const priorityOptions = [
  { label: '普通', value: 0 },
  { label: '紧急', value: 1 },
  { label: '非常紧急', value: 2 }
]
const taskTypeOption = ref([
  { label: '董事长任务', value: 1 },
  { label: '主管领导任务', value: 2 },
  { label: '日常任务', value: 3 },
  { label: '其他部门配合任务', value: 4 },
  { label: '中油国际任务', value: 5 },
  { label: '商务招标任务', value: 6 }
])
//责任人
const regionListItemRender = reactive({
  name: 'VxeTreeSelect',
  props: {
    multiple: false,
    clearable: true,
    placeholder: '请选择发布人',
    treeConfig: {
      accordion: true,
      trigger: 'node',
      showLine: false,
      isHover: true,
      indent: 20,
      radioConfig: {
        showIcon: true,
        visibleMethod({ node }) {
          return !node.disabled
        },
        checkMethod({ node }) {
          return !node.disabled
        }
      }
    }
  },
  options: []
})
//任务发布人
const responsibleListItemRender = reactive({
  name: 'VxeTreeSelect',
  props: {
    multiple: false,
    clearable: true,
    placeholder: '请选择责任人',
    treeConfig: {
      accordion: true,
      trigger: 'node',
      showLine: false,
      isHover: true,
      indent: 20,
      radioConfig: {
        showIcon: true,
        visibleMethod({ node }) {
          return !node.disabled
        },
        checkMethod({ node }) {
          return !node.disabled
        }
      }
    }
  },
  options: []
})
//任务参与人
const responsibleListItemcheckbox = reactive({
  name: 'VxeTreeSelect',
  props: {
    multiple: true,
    clearable: true,
    placeholder: '请选择参与人',
    treeConfig: {
      checkboxConfig: {
        showIcon: true,
        checkStrictly: true,
        visibleMethod({ node }) {
          return !node.disabled
        },
        checkMethod({ node }) {
          return !node.disabled
        }
      }
    }
  },
  options: []
})
//查询部门用户
const deptUsersTree = () => {
  getDeptUsersTree({}).then((res) => {
    regionListItemRender.options = res
    responsibleListItemRender.options = res
    responsibleListItemcheckbox.options = res
  })
}
// 保存用户对应的表格配置接口
const saveCustomSetting = (id, storeData) => {
  const data = {
    tableId: id,
    tableConfig: JSON.stringify(storeData)
  }
  UserConfigApi.saveOrUpdateUserConfig(data).then((res) => {
    console.log(storeData)
    VxeUI.modal.message({
      status: 'success',
      content: '保存用户个性化数据成功'
    })
  })
}
// 查询配置接口
const findCustomSetting = (id) => {
  return UserConfigApi.getUserConfig(id).then((res) => {
    console.log('res------>', JSON.parse(res.tableConfig))
    return JSON.parse(res.tableConfig)
  })
}
const getTaskType = async () => {
  const data = await MenuApi.increaseSimpleList()
  taskTypeOption.value = data
}
//表格详情
const tableOption = reactive({
  tooltipConfig: {
    showAll: true
  },
  id: 'task_chairman',
  border: true,
  stripe: true,
  loading: true,
  maxHeight: 800,
  columnConfig: {
    resizable: true,
    mode: 'modal'
  },
  editConfig: {
    trigger: 'dblclick',
    mode: 'row'
  },
  rowConfig: {
    height: 50,
    isHover: true
  },

  checkboxConfig: {
    labelField: 'checkbox',
    highlight: true
  },
  customConfig: {
    storage: true,
    restoreStore({ id }) {
      return findCustomSetting(id)
    },
    updateStore({ id, storeData }) {
      // 模拟异步，实现服务端保存
      return saveCustomSetting(id, storeData)
    },
    checkMethod({ column }) {
      return !['seq', 'urging', 'taskName', 'explanation', 'taskDetail'].includes(column.field)
    }
  },
  resizableConfig: {
    minWidth: 120,
    maxWidth: 460
  },
  toolbarConfig: {
    custom: true,
    export: false,
    zoom: true,
    slots: {
      buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  exportConfig: {
    columns: [
      { field: 'seq', type: 'seq', width: 70 },
      { field: 'taskName', width: 70 },
      { field: 'status', width: 70 },
      { field: 'publisherName', width: 70 },
      {
        field: 'taskStartTime',
        width: 70,
        formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
      },
      {
        field: 'taskEndTime',
        width: 70,
        formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
      },
      { field: 'responsibleName', width: 70 },
      { field: 'priority', width: 70 }
    ]
    // columnFilterMethod({ column }) {
    //   if (column.field === 'taskStartTime'|| column.field === 'taskEndTime') {
    //     console.log(column)
    //     // 自定义时间格式
    //     return (value) => XEUtils.toDateString(value, 'yyyy-MM-dd');
    //   }
    //   return true;
    // },
    // beforeExportMethod: (params) => {
    //   const exportData = params.options['data']; // 获取完整数据
    //   exportData.forEach(record => {
    //     record.taskEndTime = formatDate(record.taskEndTime);
    //     record.taskStartTime = formatDate(record.taskStartTime);
    //   });
    //   params.options.data = exportData; // 覆盖导出数据
    //   return true;
    // }
  },
  treeConfig: {
    rowField: 'id',
    childrenField: 'children',
    expandAll: false
  },
  data: [],
  columns: [],
  //右键菜单
  menuConfig: {
    body: {
      options: [
        [
          {
            code: 'putUp',
            name: '置顶',
            prefixConfig: { icon: 'vxe-icon-caret-up' },
            visible: true,
            disabled: false
          },
          {
            code: 'putDown',
            name: '置底',
            prefixConfig: { icon: 'vxe-icon-caret-down' },
            visible: true,
            disabled: false
          },
          {
            code: 'detail',
            name: '详情编辑',
            prefixConfig: { icon: 'vxe-icon-edit' },
            visible: true,
            disabled: false
          }
        ],
        [
          {
            code: 'deleteRow',
            name: '删除',
            prefixConfig: { icon: 'vxe-icon-delete' },
            visible: true,
            disabled: false
          }
        ],
        [
          // {
          //   code: 'insertRow',
          //   name: '插入',
          //   prefixConfig: { icon: 'vxe-icon-add' },
          //   visible: true,
          //   disabled: false
          // },
          {
            code: 'insertChild',
            name: '添加下级',
            prefixConfig: { icon: 'vxe-icon-arrow-down rotate180' },
            visible: true,
            disabled: false
          }
        ]
      ]
    }
  }
})
//表单详情
const formOptions = reactive({
  titleWidth: 140,
  titleAlign: 'left',
  titleColon: true,
  data: XEUtils.clone(defaultData, true),
  rules: {
    taskName: [
      { required: true, message: '请输入名称' },
      { min: 1, max: 50, message: '长度在 1 到 50 个字符' }
    ],
    taskEndTime: [{ required: true, message: '请输入结束时间' }],
    responsibleId: [{ required: true, message: '请选择责任人' }],
    priority: [{ required: true, message: '请选择优先级' }]
  },
  items: []
})
const formItmes = reactive([
  {
    field: 'taskName',
    title: '名称',
    span: 24,
    itemRender: {
      name: 'VxeInput',
      props: {
        clearable: true // 启用清空按钮
      }
    }
  },
  {
    field: 'taskDetail',
    title: '任务详情',
    span: 24,
    itemRender: {
      name: 'VxeTextarea',
      props: {
        clearable: true // 启用清空按钮
      }
    }
  },
  {
    field: 'publisherId',
    title: '任务发布人',
    span: 12,
    itemRender: regionListItemRender
  },
  {
    field: 'responsibleId',
    title: '责任人',
    span: 12,
    itemRender: responsibleListItemRender
  },
  {
    field: 'shareId',
    title: '任务参与人',
    span: 24,
    itemRender: responsibleListItemcheckbox
  },
  {
    field: 'status',
    title: '状态',
    span: 12,
    itemRender: {
      name: 'VxeSelect',
      optionGroups: statusOptions,
      props: {
        clearable: true // 启用清空按钮
      }
    }
  },
  {
    field: 'taskType',
    title: '任务类型',
    span: 12,
    itemRender: {
      name: 'VxeSelect',
      optionGroups: await MenuApi.increaseSimpleList(),
      props: {
        clearable: true // 启用清空按钮
      }
    }
  },
  {
    field: 'taskStartTime',
    title: '开始时间',
    span: 12,
    itemRender: {
      name: 'VxeDatePicker',
      props: {
        type: 'date',
        clearable: true
      }
    }
  },
  {
    field: 'taskEndTime',
    title: '完成时间',
    span: 12,
    itemRender: { name: 'VxeDatePicker', props: { type: 'date', clearable: true } }
  },
  {
    field: 'priority',
    title: '优先级',
    span: 12,
    itemRender: {
      name: 'VxeSelect',
      optionGroups: priorityOptions,
      props: {
        clearable: true // 启用清空按钮
      }
    }
  }
  // {
  //   field: 'explanation',
  //   title: '任务进展更新',
  //   span: 24,
  //   itemRender: { name: 'VxeTextarea',props: {
  //     clearable: true, // 启用清空按钮
  //   } },
  // }
])

export {
  priorityOptions,
  statusOptions,
  regionListItemRender,
  responsibleListItemRender,
  tableOption,
  formOptions,
  deptUsersTree,
  defaultData,
  formItmes,
  getTaskType
}
